import { Viewer, Entity, EntityCollection } from "cesium";
import type { BaseEntity } from "./BaseEntity";

/**
 * EntityManager 类用于管理 Cesium 中的实体（Entity）
 * 提供了实体的添加、删除、查询等功能
 * @class
 */
export class EntityManager {
  /** Cesium Viewer 实例 */
  private viewer: Viewer;
  /** 实体映射表，用于存储和管理所有实体 */
  static entities: Map<string, Entity> = new Map();
  private registry = new Map<string, BaseEntity>();
  /**
   * 创建 EntityManager 实例
   * @param {Viewer} viewer - Cesium Viewer 实例
   */
  constructor(viewer: Viewer) {
    this.viewer = viewer;
  }
  /**
   * 添加装备（内部方法）
   */
  add(equipment: BaseEntity): void {
    const id = equipment.entity.id.toString();

    if (this.registry.has(id)) {
      console.warn(`Equipment ${id} already exists, replacing...`);
    }

    equipment.entityManager = this;
    equipment.viewer = this.viewer;
    this.registry.set(id, equipment);

    this.addEntity(equipment.entity.id, equipment.entity);
  }
  /**
   * 删除装备（内部方法）
   */
  remove(id: string): void {
    const equipment = this.registry.get(id);

    if (!equipment) {
      console.warn(`Equipment ${id} already exists, replacing...`);
      return;
    }

    this.registry.delete(id);

    this.removeEntity(equipment.entity.id);
  }

  /**
   * 获取装备（带类型检查）
   */
  getById<T extends BaseEntity>(id: string): T | null {
    const record = this.registry.get(id);
    return (record as T) || null;
  }

  /**
   * 批量获取同类装备
   */
  getByType<T extends BaseEntity>(type: new (...args: any[]) => T): T[] {
    return [];
  }
  /**
   * 添加实体到场景中
   * @param {string} id - 实体的唯一标识符
   * @param {Entity} entity - 要添加的实体
   * @returns {Entity} 添加的实体
   */
  private addEntity(id: string, entity: Entity): Entity {
    EntityManager.entities.set(id, entity);
    this.viewer.entities.add(entity);
    return entity;
  }

  /**
   * 从场景中移除实体
   * @param {string} id - 要移除的实体的唯一标识符
   * @returns {boolean} 是否成功移除实体
   */
  private removeEntity(id: string): boolean {
    const entity = EntityManager.entities.get(id);
    if (entity) {
      this.viewer.entities.remove(entity);
      EntityManager.entities.delete(id);
      return true;
    }
    return false;
  }

  /**
   * 获取指定 ID 的实体
   * @param {string} id - 实体的唯一标识符
   * @returns {Entity | undefined} 找到的实体，如果不存在则返回 undefined
   */
  getEntity(id: string): Entity | undefined {
    return EntityManager.entities.get(id);
  }

  /**
   * 获取 Cesium 实体集合
   * @returns {EntityCollection} Cesium 实体集合
   */
  getEntityCollection(): EntityCollection {
    return this.viewer.entities;
  }
}
